package com.controller;

import com.alibaba.fastjson.JSON;
import com.dao.UserDao;
import com.entity.MyReturn;
import com.entity.Userinfo;
import com.util.Constants;
import com.util.MySqlsessionFactory;
import com.util.MyTools;
import com.util.ResultStatusEnum;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 加载数据库驱动
        SqlSession sqlSession= MySqlsessionFactory.getSQLSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        MyReturn myReturn = new MyReturn();
        // 获取输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 把当前用户名加入到session中
        request.getSession().setAttribute("username",username);
        // 通过输入的用户名获取到该用户的所有信息，以用户实体的形式返回
        List<Userinfo> list = userDao.loginUser(username);
        Userinfo userinfo = list.get(0);
        // 通过输入的密码 和 查找到的盐值 salt  加密，形成一个密文
        String newPassord = MyTools.makePassord(password,userinfo.getSalt());
        // 对比新形成的密文和当前用户数据库中存储的密文
        //      若一致，则成功登录
        //      若不一致，则登录失败
        if (newPassord.equals(userinfo.getPassword())) {
            myReturn.setCode(ResultStatusEnum.SUCCESS.getCode());
        } else {
            myReturn.setCode(ResultStatusEnum.FAILE.getCode());
            myReturn.setMsg(Constants.ERROR_Login);
        }
        // 将返回对象转为json对象
        String jsonStr = JSON.toJSONString(myReturn);
        response.getWriter().write(jsonStr);
        // 提交事务
        sqlSession.commit();
        // 关闭mysql连接
        sqlSession.close();
    }
}
